<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
	
	class Signup extends Admin_Controller{
		public function __construct(){
			parent::__construct();
			$this->load->model('database_model');
		}

		public function index(){
			$title = "Sign Up";
			$data = array(
				'header' => $title
				);
			$this->load->view('admin/signup', $data);
		}
		public function checksignup(){
			if(!serverReferer()){
				redirect('admin/login', 'refresh');
			}
			
			$username = $this->input->post('username', TRUE);
			$email    = $this->input->post('email', TRUE);
			if(!$username || !$email){
				redirect('admin/signup', 'refresh');
			}else{
				$this->load->library('form_validation');

				$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[30]|xss_clean');
				$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');

				if($this->form_validation->run() === FALSE){
					$json = array(
						'status' => '0',
						'message' => validation_errors()
						);
					echo json_encode($json);
				}else{
					$this->db->where(array('Username' => $username));
					$this->db->or_where(array('Email' => $email));
					$rs = $this->database_model->Get('ci_users');
					if($rs->num_rows() > 0){
						$json = array(
							'status'  => '0',
							'message' => 'This username or email is already registered.'
							);
						echo json_encode($json);
					}else{
						$password = random_string('alpha',8);
						$encode_password = do_hash($password, 'md5');
						$data = array(
							'Username' => $username,
							'Password' => $encode_password,
							'Email'    => $email
							);
						$insert = $this->database_model->Insert('ci_users', $data);
						if($insert){
							$json = array(
								'status' => '1',
								'message' => 'Registration complete. Please check your e-mail'
								);
							echo json_encode($json);	
						}else{
							$json = array(
								'status' => '0',
								'message' => 'Unsuccessful. Try again!'
								);
							echo json_encode($json);
						}
					}
				}
			}
		}
	}
?>